<template>
	<view class="csr-sign">
		
			<view class="sighButtons" >
				<view class="sighButtons_button" style="border: solid 1rpx #999; color: #999;background-color: #fff;margin-top: 100rpx;"  @click.tap="back">
					<p class="sighButtons_button_xiao">返回</p>
					
				</view>
				<view class="sighButtons_button" style="background: #999;" @click.tap="clearClick">
					<view class="sighButtons_button_xiao">重签</view>
				</view>
				<view class="sighButtons_button" style="background-color: #38A99A;" @click.tap="getCanvasTempFilePath">
					<view class="sighButtons_button_xiao">完成签名</view>
				</view>
			</view>
	
		<canvas 
		    id="canvas"
			canvas-id="canvas"
			@touchmove="move" 
		    @touchstart="start"  
		    @error="error"
			@touchend="touchend"
		    :style="{width:canvasWidth + 'px',height:canvasHeight + 'px'}">
		</canvas>
		
			 <tn-modal @click="sure()" :zIndex="999999" v-model="show" :title="title" :content="content" :button="button"></tn-modal>
	</view>
</template>

<script>
	export default {
		name:"csr-sign",
		props:{
			orientation:{
				type: String,
				default: 'portrait'
			},
			width:{
				type: Number,
				default: 0
			},
			height:{
				type: Number,
				default: 0
			},
			lineWidth:{
				type:Number,
				default:3
			},
			strokeStyle:{
				type:String,
				default:"black"
			}
		},
		data() {
			return {
				canvas: '',
				ctx: '',
				pr:0,
				canvasWidth:'',
				canvasHeight:'',
				points:[],
				show: false,
				      title: '上传确认',
				      content: '确认之后签名将无法进行修改',
										button: [{
										            text: '取消',
										            backgroundColor: '#E6E6E6',
										            fontColor: '#333333',
										            plain: true,
										            shape: 'round'
										          },
										          {
										            text: '确定',
										            backgroundColor: 'tn-bg-indigo',
										            fontColor: '#FFFFFF'
										          }
										        ]
			};
		},
		created(){
			this.getSystemInfo();
			this.createCanvas();
			
		},
		mounted() {
		  setTimeout(() => {
		    this.checkCanvasExistence();
		  }, 5000); // 延迟100毫秒执行检查
		},
	methods:{
		submit() {
						
		       this.show = true;
		     },
			 sure(index){
			 					  if(index.index==0){
			 						 this.show = false; 
			 					  }else{
									this.getCanvasTempFilePath();
			 					  }
			 					 
			 					  
			 },
		getCanvasTempFilePath(){
			 uni.canvasToTempFilePath({
			    canvasId: 'canvas', // canvas元素的ID
			    success: res => {
			      console.log('Canvas临时路径:', res.tempFilePath);
				    let path = res.tempFilePath;
				     this.$emit("finish",path);
			      // 在这里你可以对临时路径进行进一步处理，比如保存到本地或者发送到服务器
			    },
			    fail: err => {
			      console.error('获取Canvas临时路径失败:', err);
			    }
			  }, this);
		},
	    checkCanvasExistence() {
	        const query = uni.createSelectorQuery().in(this);
	           query.select('#canvas').boundingClientRect(data => {
	             if (!data) {
	               console.error('画板元素不存在');
	             }
	           }).exec();
	    },
	    // 触摸开始
	    start(e) {
	      
	        this.points.push({X:e.touches[0].x,Y:e.touches[0].y});
	        //每次触摸开始，开启新的路径
	        this.ctx.beginPath();
	    },
	    // 开始移动
	    move(e) {
	   
	        this.points.push({X:e.touches[0].x,Y:e.touches[0].y});       //存点
	        if(this.points.length >= 2){
	            this.draw();                   //绘制路径
	        }
	    },
	    // 触摸结束，将未绘制的点清空防止对后续路径产生干扰
	    touchend(){                  
	    
	        this.points=[];
	    },
	    draw(){
	        let point1 = this.points[0];
	        let point2 = this.points[1];
	        this.points.shift();
	        this.ctx.moveTo(point1.X, point1.Y);
	        this.ctx.lineTo(point2.X, point2.Y);
	        this.ctx.stroke();
	        this.ctx.draw(true);
	    
	    },
	    error(e) {
	        console.log("画布触摸错误" + e);
	    },
	    finish(){
	       
	         this.$nextTick(() => {
	             uni.createSelectorQuery()
	               .select('#canvas')
	               .fields({ node: true }, (res) => {
	                 if (res && res.node) {
	                   console.log('画板存在');
	                   // 画板存在，执行获取画板内容的操作
	                   this.getCanvasContent();
	                 } else {
	                   console.log('画板不存在');
	                 }
	               })
	               .exec();
	           });
	        uni.canvasToTempFilePath({
	            canvasId: 'canvas',
	            success: (res) => {
	                console.log(res,'res')
	                let path = res.tempFilePath;
	                this.$emit("finish",path);
	            }
	        })
	    },
	    clearClick () {
	        console.log('清除画布');
	        //清除画布
	        this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
	        this.ctx.draw(true);
	    },
	    back(){
	        console.log('返回事件');
	        uni.navigateBack();
	    },
	    createCanvas() {
	        const pr = this.pr; // 像素比
	        const ctx = uni.createCanvasContext('canvas',this);
	        ctx.lineGap = 'round';
	        ctx.lineJoin = 'round';
	        ctx.lineWidth = this.lineWidth; // 字体粗细
	        ctx.strokeStyle = this.strokeStyle; // 字体粗细
	        this.ctx = ctx;
	        console.log('Canvas 创建完成');
	    },
	     // 获取系统信息
	    getSystemInfo() {
	        uni.getSystemInfo({
	            success:(res) => {
	                this.pr = res.pixelRatio;
	                if(this.orientation == 'portrait'){
	                    if(this.width > res.windowWidth || this.width == 0){
	                        this.canvasWidth = res.windowWidth;
	                    }else {
	                        this.canvasWidth = this.width;
	                    }
	                    if(this.height > res.windowHeight - 70  || this.height == 0){
	                        this.canvasHeight = res.windowHeight - 70;
	                    }else{
	                        this.canvasHeight = this.height;
	                    }
	                }else if(this.orientation == 'abeam'){
	                    if(this.width > res.windowWidth - 70 || this.width == 0){
	                        this.canvasWidth = res.windowWidth - 70;
	                    }else {
	                        this.canvasWidth = this.width;
	                    }
	                    if(this.height > res.windowHeight  || this.height == 0){
	                        this.canvasHeight = res.windowHeight ;
	                    }else{
	                        this.canvasHeight = this.height;
	                    }
	                }
	                console.log('系统信息获取完成');
	            }
	        })
	    }
	}
	}
</script>

<style lang="scss">
	page {
		width: 100%;
		height: 100%;
	    background-color: #e9f2f1;
	}
	canvas {
		background-color: white;
	}
	.csr-sign{
		width: 100%;
		height: 100%;
		display: flex;
		flex-wrap: wrap;
		align-items: flex-end;
	}
	.sighButton{
		width: 690rpx;
		margin: 0rpx auto;
		height: 60px;
		padding-top:10px;
		display: flex;
		justify-content: space-between;
		&_button{
			width: 30%;
			height: 100rpx;
			border-radius: 10rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 32rpx;
			color: #fff;
		}
		
	}
	.sighButtons{
		width:70px;
		margin: 0rpx auto;
		height: 600rpx;
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		&_button{
			width: 200rpx;
			height: 55px;
			border-radius: 10rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 32rpx;
			color: #fff;
			transform: rotate(90deg);
		}
		
	}
</style>